package per.hnvcam.net.http.impl;

import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import per.hnvcam.net.http.HTTPConnection;
import per.hnvcam.searchext.Constants;
import per.hnvcam.searchext.data.dao.ConfigDAO;
import per.hnvcam.searchext.data.model.Config;

import java.io.IOException;
import java.io.InputStream;

@Service("HTTPConnection")
public class HTTPConnectionImpl implements HTTPConnection, InitializingBean {

   private boolean isUsedProxy;
   private HttpHost proxyConfiguration;
   private String proxyHost = null;
   private int proxyPort = 80;

   @Autowired
   @Qualifier("ConfigDAO")
   private ConfigDAO configDAO;

   public HTTPConnectionImpl() {
   }

   public HttpClient getClient() {
      HttpClient client = new DefaultHttpClient();
      if (proxyConfiguration != null) {
         client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyConfiguration);
      }
      return client;
   }

   private void updateProxyConfiguration() {
      proxyConfiguration = null;
      if (isUsedProxy) {
         proxyConfiguration =  new HttpHost(proxyHost, proxyPort);
      }
   }

   public void setProxy(String proxyHost, int proxyPort) {
      if (proxyHost != null && !proxyHost.isEmpty() && proxyPort > 0) {
         this.proxyHost = proxyHost;
         this.proxyPort = proxyPort;
         this.isUsedProxy = true;
      }
      else {
         this.proxyHost = null;
         this.proxyPort = 80;
         this.isUsedProxy = false;
      }
      updateProxyConfiguration();
   }

   public InputStream doGet(String url) throws IOException {
      HttpGet httpGet = new HttpGet(url);
      HttpResponse response = getClient().execute(httpGet);
      return response.getEntity().getContent();
   }

   public ConfigDAO getConfigDAO() {
      return configDAO;
   }

   @Override
   public void afterPropertiesSet() throws Exception {
      Config proxyHost = configDAO.findByProperty(Constants.PROXY_HOST);
      Config proxyPort = configDAO.findByProperty(Constants.PROXY_PORT);
      if (proxyHost != null && proxyPort != null && proxyHost.getValue() != null && proxyPort.getValue() != null &&
         !proxyHost.getValue().trim().equals("") && !proxyPort.getValue().equals("")) {
         setProxy(proxyHost.getValue(), Integer.parseInt(proxyPort.getValue()));
      }
   }
}
